import {
  KeyboardEventHandler,
  memo,
  MouseEventHandler,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from 'react';
import type { FC, PropsWithChildren } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { AutoComplete, SelectProps } from 'antd';
import { resGoods } from '@/services/goods';
import {
  localHistorySearchRecordStore,
  useLocalHistoryRecordStore,
} from '@/store/localHistorySearchRecord';
import { DeleteTwoTone, HistoryOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { useRecoilValue } from 'recoil';
import AppIcon from '@/components/AppIcon';
import {createHtml} from "@/utils/format";

export const renderTitle = (title: string) => (
  <span className={'flex items-center'}>
    <HistoryOutlined /> <span className={'ml-1'}>{title}</span>
  </span>
);

const iconStyle = { fontSize: '30' };
export const renderItem = (
  value: string,
  callback: (keyword: string) => void
) => ({
  value,
  label: (
    <div className={'flex items-center justify-between'}>
      <span>{value}</span>
      <span
        onClick={(e) => {
          e.stopPropagation();
          callback(value);
        }}
      >
        <DeleteTwoTone style={iconStyle} twoToneColor={'red'} />
      </span>
    </div>
  ),
});

const HomeInputSearch: FC<PropsWithChildren<{}>> = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams, setSearchParams] = useSearchParams();
  const [keyword, setKeyword] = useState(searchParams.get('q') || '');

  useEffect(() => {
    if (searchParams.has('q') && keyword !== searchParams.get('q')) {
      setKeyword(searchParams.get('q') || '');
    }
  }, [searchParams]);

  const onSelectHandler = (value: string) => {
    if (value.includes('/')) {
      value = value.split('/')[0];
    }
    addRecord(value);
    goSearch(value);
    setKeyword(value);
  };

  const goSearch = (q: string) => {
    if (location.pathname === '/search') {
      setSearchParams((preState) => {
        preState.set('q', q);
        return preState;
      });
      return;
    }
    navigate(`/search?q=${q}`);
  };

  const enterHandler: KeyboardEventHandler = (e) => {
    if (e.key === 'Enter') {
      if (keyword) {
        goSearch(keyword);
        addRecord(keyword);
      } else {
        goSearch('');
      }
    }
  };

  const { data, run } = useRequest(resGoods, { manual: true });

  useEffect(() => {
    run({
      limit: 10,
      attributesToHighlight: ['*'],
      filter: [
        `is_on = 1`,
        searchParams.has('category_id')
          ? `category_id = ${searchParams.get('category_id')}`
          : '',
      ],
      attributesToCrop: ['title', 'description'],
      cropLength: 10,
      q: keyword,
      highlightPreTag:"<strong class='text-blue-500 px-1' >",
      highlightPostTag:"</strong>",
    });
  }, [keyword]);

  const localHistoryRecords = useRecoilValue(localHistorySearchRecordStore);
  const { addRecord, deleteRecord } = useLocalHistoryRecordStore();
  const renderOptions = useMemo(() => {
    const renderOption: SelectProps['options'] = [
      {
        label: renderTitle('搜索记录 - 最近五条'),
        options: localHistoryRecords.map((value) =>
          renderItem(value.keyword, deleteRecord)
        ),
      },
    ];

    return (keyword === '' || !data || data.hits.length === 0) &&
      localHistoryRecords.length
      ? renderOption
      : data?.hits.map((value) => ({
          label: (
            <div
              dangerouslySetInnerHTML={createHtml(
                value._formatted.title + ' / ' + value._formatted.description
              )}
            />
          ),
          value: value.title + '/' + value.id,
        }));
  }, [localHistoryRecords, data]);
  return (
    <AutoComplete
      dropdownMatchSelectWidth={500}
      className={'w-[55%] search-section'}
      options={renderOptions}
      onSelect={onSelectHandler}
    >
      <div className={'flex-justify-items-center relative m-auto'}>
        <input
          className={
            'text-black bg-blue-50 focus:bg-white rounded-full w-full transition-all duration-300 focus:shadow-lg  focus:shadow-sky-300 focus:ring-offset-4 ring-offset-blue-100 ring-2 px-10 py-1.5 outline-0'
          }
          value={keyword}
          onKeyUp={enterHandler}
          onChange={(e) => {
            setKeyword(e.target.value);
          }}
        />
        <AppIcon
          icon={'icon-Search'}
          className={'absolute left-3 home-search search-icon'}
        />
        <button
          className={
            'rounded-full duration-300 px-5 py-0.5 right-1 bg-white hover:bg-blue-400 ring-2 hover:ring-offset-1 absolute '
          }
          onClick={async (e) => {
            if (keyword) {
              await addRecord(keyword);
              goSearch(keyword);
            } else {
              goSearch('');
            }
          }}
        >
          搜 索
        </button>
      </div>
    </AutoComplete>
  );
};

export default memo(HomeInputSearch);
